package com.itheima.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("==========路径============>"+request.getRequestURL());

        //1. 获取token
        String token = request.getHeader("Authorization");

        //2. 校验token是否有效，万一过时，万一是其他人乱搞数据
        if(!JwtUtils.verifyToken(token)){
            response.setStatus(401);
            return false;
        }
        //3. 解析token
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");
        String mobile = (String) claims.get("mobile");
        //4. 把token的数据封装到User对象
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);
        //5. 把当前登陆者的User对象存储到ThreadLocal中，这样子Controller与service才可以使用。
        UserHolder.set(user);

        return true;
    }
}
